import org.apache.poi.POIXMLTextExtractor;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName: WordUtils
 * @author: zyx
 * @E-mail: 1377631190@qq.com
 * @DATE: 2020/2/1 12:58
 */
public class WordUtils {

    /**
     * 读取word文件中的内容
     * @param path  word文件的路径
     * @return  返回word中的内容
     */
    public static String wordContent(String path) {
        try {
            //读取word文件
            String buffer = "";
            if (path.endsWith(".doc")) {
                WordExtractor wordExtractor = new WordExtractor(new FileInputStream(path));
                return wordExtractor.getText();
            } else if (path.endsWith("docx")) {
                XWPFDocument xdoc = new XWPFDocument(new FileInputStream(path));
                POIXMLTextExtractor extractor = new XWPFWordExtractor(xdoc);
                return extractor.getText();
            } else {
                System.out.println("此文件不是word文件！");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws IOException {
        System.out.println("开始搜索文件路径......");
        String file = "C:\\Users\\xxx\\Desktop\\父文件夹";
        List<MyFile> filePaths = FileUtils.filePaths(file);
        System.out.println("文件路径搜索完毕，开始读取文件内容");
        double size = filePaths.size();
        int i = 0;
        for (MyFile myFile:filePaths) {
            String content = wordContent(myFile.getAbsolutePath());
            i++;
            double v = i / size * 100;
            System.out.println("文件内容读取已完成：" + String.format("%.2f", v) + "%");
            String[] contents = StringUtils.getSpiltMessage(content);
            myFile.setContents(Arrays.asList(contents));
        }
        System.out.println("文件内容读取完毕，开始写入表格");
        ExcelUtils.writeExcel(filePaths, file + ".xlsx");
        System.out.println("写入完成");
    }
}
